

package com.kimo.shop.sys.controller;


import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.common.annotation.SysLog;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.i18n.I18nMessage;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.security.admin.util.SecurityUtils;
import com.kimo.shop.sys.dto.UpdatePasswordDto;
import com.kimo.shop.sys.model.SysUser;
import com.kimo.shop.sys.service.SysRoleService;
import com.kimo.shop.sys.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 系统用户
 * @author kimo-taozhouchuan
 */
@RestController
@RequestMapping("/sys/user")
@RequiredArgsConstructor
public class SysUserController {

	@Value("${kimo.expose.permission:}")
	private Boolean permission;

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private PasswordEncoder passwordEncoder;

	/**
	 * 所有用户列表
	 */
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('sys:user:page')")
	public ResponseEntity<IPage<SysUser>> page(String username,PageParam<SysUser> page){

		IPage<SysUser> sysUserPage = sysUserService.page(page, new LambdaQueryWrapper<SysUser>()
				.eq(SysUser::getShopId, SecurityUtils.getSysUser().getShopId())
				.like(StrUtil.isNotBlank(username), SysUser::getUsername, username));
		if (BooleanUtil.isFalse(permission)){
			for (SysUser record : sysUserPage.getRecords()) {
				record.setMobile(PhoneUtil.hideBetween(record.getMobile()).toString());
			}
		}

		return ResponseEntity.ok(sysUserPage);
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public ResponseEntity<SysUser> info(){
		return ResponseEntity.ok(sysUserService.getSysUserById(SecurityUtils.getSysUser().getUserId()));
	}

	/**
	 * 获取用户信息
	 */
	@GetMapping("/sysUserInfo")
	@PreAuthorize("@pms.hasPermission('sys:user:info')")
	public ResponseEntity<SysUser> sysUserInfo(){
		SysUser user = sysUserService.getSysUserById(SecurityUtils.getSysUser().getUserId());
		user.setUserId(null);
		user.setPassword(null);
		return ResponseEntity.ok(user);
	}

	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	@ApiOperation(value="修改密码", notes="修改当前登陆用户的密码")
	public ResponseEntity<String> password(@RequestBody @Valid UpdatePasswordDto param){
		Long userId = SecurityUtils.getSysUser().getUserId();

		SysUser dbUser = sysUserService.getSysUserById(userId);
		if (!passwordEncoder.matches(param.getPassword(), dbUser.getPassword())) {
			// 原密码不正确
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.password.error"));
		}
		//新密码
		String newPassword = passwordEncoder.encode(param.getNewPassword());
//		更新密码
		sysUserService.updatePasswordByUserId(userId, newPassword);
		return ResponseEntity.ok().build();
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@PreAuthorize("@pms.hasPermission('sys:user:info')")
	public ResponseEntity<SysUser> info(@PathVariable("userId") Long userId){
		SysUser user = sysUserService.getSysUserById(userId);
		if (BooleanUtil.isFalse(permission)){
			user.setMobile(PhoneUtil.hideBetween(user.getMobile()).toString());
		}
		user.setUserId(null);
		if (!Objects.equals(user.getShopId(), SecurityUtils.getSysUser().getShopId())) {
			// 没有权限获取该用户信息
			throw new KimoShopBindException("kimo.user.no.exist");
		}
		//获取用户所属的角色列表
		List<Long> roleIdList = sysRoleService.listRoleIdByUserId(userId);
		user.setRoleIdList(roleIdList);
		return ResponseEntity.ok(user);
	}

	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys:user:save')")
	public ResponseEntity<String> save(@Valid @RequestBody SysUser user){
		String username = user.getUsername();
		SysUser dbUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
				.eq(SysUser::getUsername, username));
		if (dbUser!=null) {
			// 该用户已存在
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.sys.user.already"));
		}
		user.setShopId(SecurityUtils.getSysUser().getShopId());
		user.setPassword(passwordEncoder.encode(user.getPassword()));
		sysUserService.saveUserAndUserRole(user);

		return ResponseEntity.ok().build();
	}

	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys:user:update')")
	public ResponseEntity<String> update(@Valid @RequestBody SysUser user){
		String password = user.getPassword();

		SysUser dbUser = sysUserService.getSysUserById(user.getUserId());

		if (!Objects.equals(dbUser.getShopId(), SecurityUtils.getSysUser().getShopId())) {
			// 没有权限修改该用户信息
			throw new KimoShopBindException("kimo.user.update.no.auth");
		}
		SysUser dbUserNameInfo = sysUserService.getByUserName(user.getUsername());

		if (dbUserNameInfo != null && !Objects.equals(dbUserNameInfo.getUserId(),user.getUserId())) {
			// 该用户已存在
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.sys.user.already"));
		}
		if (StrUtil.isBlank(password)) {
			user.setPassword(null);
		}else {
			user.setPassword(passwordEncoder.encode(user.getPassword()));
		}
		sysUserService.updateUserAndUserRole(user);
		return ResponseEntity.ok().build();
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@DeleteMapping
	@PreAuthorize("@pms.hasPermission('sys:user:delete')")
	public ResponseEntity<String> delete(@RequestBody Long[] userIds){
		if (userIds.length == 0) {
			// 请选择需要删除的用户
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.sys.select.user"));
		}
		if(ArrayUtil.contains(userIds, Constant.SUPER_ADMIN_ID)){
			// 系统管理员不能删除
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.sys.admin.error"));
		}
		if(ArrayUtil.contains(userIds, SecurityUtils.getSysUser().getUserId())){
			// 当前用户不能删除
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("kimo.sys.delete.error"));
		}
		sysUserService.deleteBatch(userIds,SecurityUtils.getSysUser().getShopId());
		return ResponseEntity.ok().build();
	}


}
